package com.hbean.controller;

import com.github.pagehelper.PageInfo;
import com.hbean.entity.SysMenu;
import com.hbean.entity.SysRoleMenu;
import com.hbean.entity.SysUser;
import com.hbean.entity.SysUserRole;
import com.hbean.service.SysMenuService;
import com.hbean.service.SysRoleMenuService;
import com.hbean.service.SysUserRoleService;
import com.hbean.service.SysUserService;
import com.hbean.system.annotation.LogMethod;
import com.hbean.system.config.Base;
import com.hbean.system.config.SysCache;
import com.hbean.utils.Condition;
import com.hbean.utils.HUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: null
 * @Project: hbean
 * @Author: hjibo
 * @CreateDate: 2018-09-30 01:05
 * @ModificationHistory:
 */

@Slf4j
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends Base {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysCache sysCache;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * description: 查询
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/getSysUsers")
    public Map getSysUsers(HttpServletRequest request){
        List<SysUser> list = null;
        try {
            //查询条件
            Condition condition = new Condition();
            condition.setParam11(request.getParameter("page"));//页码
            condition.setParam12(request.getParameter("limit"));//每页显示数量

            if(HUtil.isNotEmpty(request.getParameter("su00"))) condition.setParam1(request.getParameter("su00"));//主键
            if(HUtil.isNotEmpty(request.getParameter("startTime"))) condition.setParam2(request.getParameter("startTime") + " 00:00:00");//开始时间
            if(HUtil.isNotEmpty(request.getParameter("endTime"))) condition.setParam3(request.getParameter("endTime") + " 23:59:59");//结束时间
            if(HUtil.isNotEmpty(request.getParameter("su01"))) condition.setParam4(request.getParameter("su01"));//姓名
            if(HUtil.isNotEmpty(request.getParameter("su05"))) condition.setParam5(request.getParameter("su05"));//登录名
            if(HUtil.isNotEmpty(request.getParameter("su13"))) condition.setParam6(request.getParameter("su13"));//身份证号

            list = this.sysUserService.getDatas(condition);
            return mapResult(SUCCESS_CODE,SUCCESS_MSG,new PageInfo<>(list).getTotal(),list);
        } catch (Exception e) {
            log.info("获取用户信息失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 新增
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/addSysUser")
    @LogMethod(logName = "新增用户")
    public Map insertSysUser(HttpServletRequest request){

        try {
            String jsonStr = request.getParameter("jsonStr");
            SysUser sysUser = (SysUser) HUtil.jsonStrToJavaObject(jsonStr,SysUser.class);

            this.sysUserService.insertDataAndUpdateCache(sysUser);
            return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,null);
        } catch (Exception e) {
            log.info("保存用户信息失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 删除
     * create_user: hjibo
     * create_date: 2018-09-29 10:13
     * param :
     */
    @RequestMapping("/removeSysUsers")
    @LogMethod(logName = "删除用户")
    public Map removeSysUsers(HttpServletRequest request){

        try {
            SysUser sysUser = new SysUser();
            sysUser.setTemp1(request.getParameter("ids"));
            this.sysUserService.deleteDataAndUpdateCache(sysUser);
            return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,null);
        } catch (Exception e) {
            log.info("删除用户信息出现异常");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 修改
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/modSysUser")
    @LogMethod(logName = "修改用户")
    public Map modSysUser(HttpServletRequest request){

        try {
            String jsonStr = request.getParameter("jsonStr");
            SysUser sysUser = (SysUser) HUtil.jsonStrToJavaObject(jsonStr,SysUser.class);

            this.sysUserService.updateDataAndUpdateCache(sysUser);
            return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,null);
        } catch (Exception e) {
            log.info("修改用户信息失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 新增
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/addSysUserRole")
    @LogMethod(logName = "关联用户角色")
    public Map addSysUserRole(HttpServletRequest request){

        try {
            String jsonStr = request.getParameter("jsonStr");

            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setTemp1(jsonStr);
            this.sysUserRoleService.insertDataAndUpdateCache(sysUserRole);

            return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,null);
        } catch (Exception e) {
            log.info("保存用户信息失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 解锁
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/doUnlock")
    @LogMethod(logName = "页面解锁")
    public Map doUnlock(HttpServletRequest request){

        try {
            String jsonStr = request.getParameter("jsonStr");

            String id = HUtil.jsonStrToKeyValue(jsonStr,"id");
            String password = HUtil.jsonStrToKeyValue(jsonStr,"password");

            if(HUtil.md5Encrypt(password).equals(sysCache.getSysUserByID(id).getSu06())){
                return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,null);
            }
        } catch (Exception e) {
            log.info("解锁失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 修改密码
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/modPassword")
    @LogMethod(logName = "修改密码")
    public Map modPassword(HttpServletRequest request,HttpSession session){

        try {
            String jsonStr = request.getParameter("jsonStr");
            String oldPassword = HUtil.jsonStrToKeyValue(jsonStr,"oldPassword");
            String newPassword = HUtil.jsonStrToKeyValue(jsonStr,"newPassword");
            String password  = sysCache.getSysUserByID((String) session.getAttribute("userId")).getSu06();

            if(password.equals(HUtil.md5Encrypt(oldPassword))){
                SysUser sysUser = new SysUser();
                sysUser.setSu00((String) session.getAttribute("userId"));
                sysUser.setSu06(HUtil.md5Encrypt(newPassword));
                this.sysUserService.updateDataAndUpdateCache(sysUser);
                return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,null);
            }
        } catch (Exception e) {
            log.info("修改密码失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }

    /**
     * description: 获取个人菜单信息
     * create_user: hjibo
     * create_date: 2018-09-29 10:19
     * param :
     */
    @RequestMapping("/getMenus")
    public Map getmenus0(HttpSession session){

        try {
            //获取个人菜单
            String myRoleIds = sysCache.getSysUserRoleByUserID((String) session.getAttribute("userId"));//用户具有的角色
            Map menuMap = new HashMap();
            Optional.ofNullable(myRoleIds).ifPresent(s -> {
                List<String> myRoleIdlist = HUtil.stringToList(s,",");
                List<SysRoleMenu> SysRoleMenu = this.sysRoleMenuService.getDataForCache();//从缓存获取数据
                HashSet<String> menuIds = new HashSet<>();//用户拥有的菜单
                myRoleIdlist.forEach(s1 -> {
                    SysRoleMenu.forEach(sysRoleMenu -> {
                        if(s1.equals(sysRoleMenu.getSrm01())){
                            menuIds.add(sysRoleMenu.getSrm02());
                        }
                    });
                });
                List<SysMenu> sysMenus0 = this.sysMenuService.getDataForCache();//从缓存获取数据
                List<SysMenu> sysMenus = sysMenus0.stream().filter(sysMenu -> sysMenu.getSm10() == 1).collect(Collectors.toList());
                List<SysMenu> leftMenus = new ArrayList<>();
                HashSet<String> menuPids = new HashSet<>();//用户拥有的父菜单
                menuIds.forEach(s1 -> {
                    sysMenus.forEach(sysMenu -> {
                        if(s1.equals(sysMenu.getSm02())){
                            leftMenus.add(sysMenu);
                            menuPids.add(sysMenu.getSm03());
                        }
                    });
                });
                List<SysMenu> topMenus = new ArrayList<>();
                menuPids.forEach(s1 -> {
                    sysMenus.forEach(sysMenu -> {
                        if(s1.equals(sysMenu.getSm02())){
                            topMenus.add(sysMenu);
                        }
                    });
                });

                menuMap.put("leftMenus",leftMenus);
                menuMap.put("topMenus",topMenus);

            });
            return mapResult(SUCCESS_CODE,SUCCESS_MSG,LONG_0L,menuMap);

        } catch (Exception e) {
            log.info("获取个人菜单信息失败！");
            e.printStackTrace();
        }
        return mapResult(ERROR_CODE,ERROR_MSG,LONG_0L,null);
    }


}
